package com.wetao.lib_common.tupu;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.EventBus.bean.TpData_command;
import com.wetao.lib_common.R;
import com.wetao.lib_common.R2;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.service.PlayService;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

@Route(path = ConstantArouter.PATH_COMMON_TUPUAUIOACTIVITY)
public class CommonTupuAudioActivity extends BaseActivity<EmptyCon.View, EmptyPre>
        implements EmptyCon.View {
    @Autowired
    int gridId;
    @Autowired
    String url;
    @Autowired
    String name;

    @BindView(R2.id.tv_title)
    TextView tv_title;
    @BindView(R2.id.iv_play_or_pause)
    ImageView iv_play_or_pause;
    @BindView(R2.id.rsb_audio_progress)
    RangeSeekBar rsb_audio_progress;
    @BindView(R2.id.tv_time)
    TextView tv_time;
    @BindView(R2.id.iv_mute)
    ImageView iv_mute;
    @BindView(R2.id.rsb_vol_progress)
    RangeSeekBar rsb_vol_progress;


    private PlayService playService;
    private PlayService.PlayBinder playBinder;
    private int mDuration;  // 音频总时长
    private float rsb_fromUser_value = 0;  //拖动位置值

    private boolean mIsMute = false;
    private int mMaxValue = 0;
    private int mCurValue;
    private int rsb_fromUser_vol;
    private SettingsContentObserver mSettingsContentObserver;


    @Override
    public int getLayoutId() {
        return R.layout.common_tupu_audio_activity;
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }

    @Override
    public EmptyPre createPresenter() {
        return new EmptyPre(this);
    }

    @Override
    public EmptyCon.View createView() {
        return this;
    }

    @Override
    public void init() {
        EventBus.getDefault().register(this);
        registerVolumeChangeReceiver();
        tv_title.setText(name);
        initPlayService();
        listenerRangeChanged();
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        int max = am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);// 0
        int current= am.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
        Log.e("service", "通话音量值：" + max + "-" + current);

        max = am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);// 1
        current = am.getStreamVolume(AudioManager.STREAM_SYSTEM);
        Log.e("service", "系统音量值：" + max + "-" + current);

        max = am.getStreamMaxVolume(AudioManager.STREAM_RING);// 2
        current = am.getStreamVolume(AudioManager.STREAM_RING);
        Log.e("service", "系统铃声值：" + max + "-" + current);

        max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);// 3
        current = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        Log.e("service", "音乐音量值：" + max + "-" + current);

        mMaxValue = max;
        mCurValue = current;

        max = am.getStreamMaxVolume(AudioManager.STREAM_ALARM);// 4
        current = am.getStreamVolume(AudioManager.STREAM_ALARM);
        Log.e("service", "闹铃音量值：" + max + "-" + current);

        max = am.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);// 5
        current = am
                .getStreamVolume(AudioManager.STREAM_NOTIFICATION);
        Log.e("service", "提示声音音量值：" + max + "-" + current);


        if(mCurValue == 0) {
            mIsMute = true;
        }
        rsb_vol_progress.setRange(0, mMaxValue);
        refreshMute();

    }

    private void sysVolChange() {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int val = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        if(mIsMute && val == 0) {
        } else {
            mCurValue = val;
            if (mCurValue == 0) {
                mIsMute = true;
            } else {
                mIsMute = false;
            }
            refreshMute();
            rsb_vol_progress.setProgress(mCurValue);
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (playBinder != null) {
            playBinder.callPauseMusic();
        }
        finish();
    }
    @Override
    protected void onDestroy() {
        if(playConnection != null) {
            unbindService(playConnection);
            playConnection = null;
        }
        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_AUDIO_OUT, null));
        EventBus.getDefault().unregister(this);
        unregisterVolumeChangeReceiver();
        super.onDestroy();

        if(playBinder != null) {
            playBinder = null;
        }
        if(playService != null) {
            playService.setCallback(null);
            playService = null;
        }
    }
    @OnClick({R2.id.iv_back,
            R2.id.iv_play_or_pause,
            R2.id.iv_mute,

    })
    public void onClickView(View v) {
        int id = v.getId();
        if(id == R.id.iv_back) {
            finish();
        } else if(id == R.id.iv_play_or_pause) {
            if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                //暂停
                playBinder.callPauseMusic();
            } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE
                    || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_IDE
            ) {
                //恢复
                playBinder.callPlayMusic();
            } else if(playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_STOP
                    || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_COMPLETE) {
                if(url != null) {
                    mDuration = 0;
                    setPlayMusicUrl(url);
                }
            }
        } else if(id == R.id.iv_mute) {
            if(mIsMute) {
                mIsMute = false;
                if(mCurValue == 0) {
                    mCurValue = mMaxValue / 2;
                }
                setVol(mCurValue);
            } else {
                mIsMute = true;
                setVol(0);
            }
            refreshMute();
        }
    }

    private  void refreshMute() {
        if(mIsMute) {
            iv_mute.setImageResource(R.drawable.common_audio_jin);
        } else {
            iv_mute.setImageResource(R.drawable.common_audio_yin);
        }
    }

    private void setVol(int vol) {
        AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.setStreamVolume (AudioManager.STREAM_MUSIC , vol, 0);
    }

    private void registerVolumeChangeReceiver() {
        mSettingsContentObserver = new SettingsContentObserver(this, new Handler());
        getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);
    }

    private void unregisterVolumeChangeReceiver(){
        getApplicationContext().getContentResolver().unregisterContentObserver(mSettingsContentObserver);
    }

    public class SettingsContentObserver extends ContentObserver {
        Context context;

        public SettingsContentObserver(Context c, Handler handler) {
            super(handler);
            context = c;
        }

        @Override
        public boolean deliverSelfNotifications() {
            return super.deliverSelfNotifications();
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            sysVolChange();
        }
    }

    private void silentSwitchOn() {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if(audioManager != null){
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            audioManager.getStreamVolume(AudioManager.STREAM_RING);
            LogUtils.i("音量模式RINGING 已被静音");
            refreshMute();
        }
    }

    private void silentSwitchOff() {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if(audioManager != null){
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            audioManager.getStreamVolume(AudioManager.STREAM_RING);
            LogUtils.i("音量模式RINGING 取消静音");
            refreshMute();
        }
    }


    /**
     * 初始化音频播放服务
     */
    private void initPlayService() {
        Intent playService = new Intent(this, PlayService.class);
        this.bindService(playService, playConnection, Service.BIND_AUTO_CREATE);
    }

    /**
     * 播放音频
     * @param url
     */
    private void setPlayMusicUrl(String url) {
        if (playBinder != null) {
            playBinder.callSetmUrl(url);
        }
    }

    private void updateCurrentTime(int cur, int duration) {
        String audioTime;
        if (duration < 0 || cur == 0){
            audioTime = String.format("%s/%s", "00:00", ComUtil.strToTime(duration / 1000 + ""));
        }else {
            audioTime = String.format("%s/%s", ComUtil.strToTime(cur / 1000 + ""), ComUtil.strToTime(duration / 1000 + ""));
        }

        tv_time.setText(audioTime);

    }

    /**
     * 音频拖动监听
     */
    private void listenerRangeChanged() {

        rsb_audio_progress.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if(isFromUser) {
                    rsb_fromUser_value = leftValue;
                    LogUtils.i("rsb_audio_progress: onRangeChanged -- leftValue = " + leftValue + ", rightValue = " + rightValue + ", isFromUser = " + isFromUser);

                }
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
                int cur = (int) (rsb_fromUser_value / view.getMaxProgress() * mDuration);
                if (playBinder != null &&  playBinder.callPlayStatus() != PlayService.STATUS_MUSIC_IDE_PRE){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateCurrentTime(cur,mDuration);
                        }
                    });

                    playBinder.callSeekTo(cur);
                }
            }
        });

        rsb_vol_progress.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if(isFromUser) {
                    rsb_fromUser_vol = (int)leftValue;
                    LogUtils.i("rsb_audio_progress: onRangeChanged -- leftValue = " + leftValue + ", rightValue = " + rightValue + ", isFromUser = " + isFromUser);

                }
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
                mCurValue = rsb_fromUser_vol;
                if(mCurValue == 0) {
                    mIsMute = true;
                } else {
                    mIsMute = false;
                }
                setVol(mCurValue);
                refreshMute();
            }
        });
    }

    private ServiceConnection playConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            playBinder = (PlayService.PlayBinder) service;
            playService = playBinder.getService();
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_AUDIO_INTO, null));

            playService.setCallback(new PlayService.CallbackPlay() {
                @Override
                public void onDataTestChange(String data) {

                }

                @Override
                public void onMusicStausChange(int status) {
                    iv_play_or_pause.setImageResource(R.drawable.common_audio_play);
                    if(status == PlayService.STATUS_MUSIC_PLAY) {
                        iv_play_or_pause.setImageResource(R.drawable.common_audio_pause);
                    }
                }

                @Override
                public void onCurrentPosition(int currentPosition, int duration) {
                    runOnUiThread(() -> {
                        if (duration > 0 && currentPosition <= duration) {
                            if(mDuration == 0 && duration != 0) {
                                mDuration = duration;
                                rsb_audio_progress.setRange(0, mDuration);
                            } else if(mDuration != 0){
                                rsb_audio_progress.setProgress(currentPosition);
                            }
                            updateCurrentTime(currentPosition, duration);
                        }
                    });
                }

                @Override
                public void onCompletion() {

                }

                @Override
                public void OnDuration(int duration) {

                }

                @Override
                public void onLoadedUrl() {
                    if (playBinder != null) {
                        playBinder.callPlayMusic();
                    }
                }
            });
            setPlayMusicUrl(url);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busGetMessage(EventBusMessage messageEvent) {
        LogUtils.i("m1: bus-->" + messageEvent.toString());
        int action = messageEvent.getAction();
        String msg = messageEvent.getMsg();
        if(action == EventBusMessage.EVENT_BUS_ACTION_DATA_TP) {
            TpData_command cm = JsonUtils.fromJson(msg, TpData_command.class);
            if(cm.getId().intValue() == gridId && cm.getUrl().equals(url)) {

                //点击的是同一个格子，播放暂停
                if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                    //暂停
                    playBinder.callPauseMusic();
                } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE
                        || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_IDE
                ) {
                    //恢复
                    playBinder.callPlayMusic();
                } else if(playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_STOP
                        || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_COMPLETE) {
                    if(url != null) {
                        mDuration = 0;
                        setPlayMusicUrl(url);
                    }
                }
            } else {
                gridId = cm.getId().intValue();
                url = cm.getUrl();
                name = cm.getName();
                mDuration = 0;
                tv_title.setText(cm.getName());
                setPlayMusicUrl(url);
            }
        }
    }
}
